# -*- coding: utf-8 -*-
import sys

from flask import Blueprint
from common import success_resp
from celery_tasks.sample.tasks import async_add
from celery_tasks.sample.tasks import async_add_2
from celery_tasks.sample.tasks import test_mes

sample_bp = Blueprint('sample', __name__)


@sample_bp.get('/add')
def add():
    async_add.delay(5, 8)
    return success_resp(msg='任务执行完成')


@sample_bp.get('/add2')
def add_2():
    async_add_2.delay(5, 8)
    return success_resp(msg='任务执行完成--2')


@sample_bp.get('/mes')
def mes():
    r = test_mes.delay()
    print(r.get(on_message=pm, propagate=False))
    return success_resp(msg='任务执行完成 mes')


def pm(body):
    res = body.get('result')
    if body.get('status') == 'PROGRESS':
        sys.stdout.write('\r任务进度: {0}%'.format(res.get('p')))
        sys.stdout.flush()
    else:
        print('\r')
        print(res)
